package summer.backtracking;

import java.util.ArrayList;
import java.util.List;

public class Solution39 {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtracking(candidates, 0, target, 0);
        return res;
    }

    public void backtracking(int[] candidates, int index, int target, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        if (sum > target || index == candidates.length) return;
        for (int i = index; i < candidates.length; i++) {
            tmp.add(candidates[i]);
            sum += candidates[i];
            backtracking(candidates, i, target, sum);
            sum -= candidates[i];
            tmp.remove(tmp.size() - 1);
        }
    }
}


